<?php
namespace Purse\Model;
use Think\Model;
class RedPacketsDetailModel extends Model {
	protected $connection = 'DB_BASE_DSN';
	protected $tableName = 'qyx_redpackets_detail'; 
	
	
	public function getPacketsList($data){
		$map = array();
		if(!empty($data['packetsid'])){
			$map['qyx_redpackets_detail.packetsid'] = $data['packetsid'];
		}
		
		if(!empty($data['custid'])){
			$map['qyx_redpackets_detail.custid'] = $data['custid'];
		}
	
		if(!empty($data['year'])){
			//$map['qyx_redpackets_detail.createtime'] = array('egt' , $data['year']);
			//$map['qyx_redpackets_detail.createtime'] = array('elt' , $data['year']+1);
			
			$map['qyx_redpackets_detail.createtime'] = array('between',array("{$data['year']}",$data['year']+1));
		}
		
		$luckmap = $map;
		$luckmap['isluck'] = 1;
	
		$totalamount = $this->join('qyx_redpackets on qyx_redpackets_detail.packetsid = qyx_redpackets.packetsid')
				->field('qyx_redpackets_detail.custid,sum(qyx_redpackets_detail.amount) as totalamount')
				->where($map)->group('qyx_redpackets_detail.custid')->select();
		
		$total = $this->join('qyx_redpackets on qyx_redpackets_detail.packetsid = qyx_redpackets.packetsid')->where($map)->count();
		$lucktotal = $this->join('qyx_redpackets on qyx_redpackets_detail.packetsid = qyx_redpackets.packetsid')->where($luckmap)->count();
		$fields = array('qyx_redpackets_detail.id','qyx_redpackets_detail.packetsid','qyx_redpackets_detail.custid','qyx_redpackets_detail.chatid',
						'qyx_redpackets_detail.fcustid','qyx_redpackets_detail.amount','qyx_redpackets_detail.isluck','qyx_redpackets_detail.thankswords',
						'qyx_redpackets.type',
						'qyx_redpackets_detail.createtime','qyx_redpackets_detail.updatetime');
	
		if(empty($data['sortField']))$data['sortField'] = "qyx_redpackets_detail.id";
		if(empty($data['sortOrder']))$data['sortOrder'] = "desc";
	
		if(empty($data['pageSize']) && empty($data['pageIndex']))
			$result = $this->join('qyx_redpackets on qyx_redpackets_detail.packetsid = qyx_redpackets.packetsid')->field($fields)->where($map)->order("{$data['sortField']} {$data['sortOrder']}")->select();
		else
			$result = $this->join('qyx_redpackets on qyx_redpackets_detail.packetsid = qyx_redpackets.packetsid')->field($fields)->where($map)->order("{$data['sortField']} {$data['sortOrder']}")->limit($data['pageIndex']*$data['pageSize'] , $data['pageSize'])->select();
	
		return array('totalamount'=>$totalamount , 'total'=>$total , 'lucktotal'=>$lucktotal , 'data'=>$result);
	}
	
	public function addPacketsDetail($data){
		$result = $this->add($data);
		return $result;
	}
	
	
	public function updatePacketsDetail($data){
		$map['packetsid'] = $data['packetsid'];
		$map['custid'] = $data['custid'];
		$data['updatetime'] = date("Y-m-d H:i:s");
		$result = $this->where($map)->save($data);
		return $result;
	}
}


